package cn.com.taiji.pos.controller.Abandoned;

import cn.com.taiji.pos.common.util.HttpUtil;
import cn.com.taiji.pos.common.util.SmallTicketPrinter;
import cn.com.taiji.pos.common.util.pay.wxpay.WXPay;
import cn.com.taiji.pos.common.util.pay.wxpay.WXPayConfigImpl;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Controller
//@RequestMapping("/test")
public class TestController {

    @Value("${FOOD_CATEGORY_ID_CODE_xmb}")
    private String FOOD_CATEGORY_ID_CODE_xmb;
    @Value("${GET_COMMISSARY_FOOD_URL}")
    private String GET_COMMISSARY_FOOD_URL;
    @Value("${COMMISSARY_BUSINESS_TYPE_ID}")
    private String COMMISSARY_BUSINESS_TYPE_ID;
    @Autowired
    private IMenuFoodItemService menuFoodItemService;
    @Autowired
    private IMenuFoodPriceService menuFoodPriceService;
    @Autowired
    private ICardAccountService cardAccountService;
    @Autowired
    private IConfigCauseService configCauseService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private ITradeConsumptionMainService tradeConsumptionMainService;
    @Autowired
    private SmallTicketPrinter smallTicketPrinter;
    @Autowired
    private ITradeConsumptionDetailService tradeConsumptionDetailService;
    @Autowired
    private ITradeAccountConsumptionFlowService tradeAccountConsumptionFlowService;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private ISystemRefundApprovalService systemRefundApprovalService;
    @Autowired
    private ISystemAclUserService systemAclUserService;
    @Autowired
    private IMenuFoodCategoryService menuFoodCategoryService;

    @RequestMapping("test1")
    public String test1() {


//        List<MenuFoodItem> menuFoodItem = menuFoodItemService.selectFoodItemList();
//        MenuFoodItem byId = menuFoodItemService.getById("1775ddab7c4547a3ad5fb53969b36747");

//        List<MenuFoodItem> foodItemList = menuFoodItemService.listXMBFood("6953787338429", FOOD_CATEGORY_ID_CODE_xmb);

//        List<CardAccount> CardAccount = cardAccountService.findCardAccountList("820c09b7a4294333b352c997d9613bda", "午餐");

        List<SystemRefundApproval> systemRefundApprovalList = systemRefundApprovalService.list();

        return JSONObject.toJSONString(systemRefundApprovalList);
    }

    @RequestMapping("test2")
    public String test2(Model model) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        QueryWrapper<ConfigMealTime> configMealTimeWrapper = new QueryWrapper<>();
        configMealTimeWrapper.le("START_TIME", df.format(LocalDate.now()));
        configMealTimeWrapper.ge("END_TIME", df.format(LocalDate.now()));
        ConfigMealTime configMealTime = configMealTimeService.getOne(configMealTimeWrapper, false);
        return JSONObject.toJSONString(configMealTime);
    }

    @RequestMapping("test3")
    public String test3(Model model) {
        TradeConsumptionMain list = tradeConsumptionMainService.getById("f5c2173d8af0492cbfceb67c8108911d");
//        model.addAttribute("test","list");
//        model.addAttribute("test2",0);
//        model.addAttribute("test3",list);
//        model.addAttribute("test4",list);
        return JSONObject.toJSONString(model);
    }

    @RequestMapping("test4")
    public String test4(Model model) {
        TradeAccountConsumptionFlow byId = tradeAccountConsumptionFlowService.getById("007ad135c44d4649b696de5a6348fded");


        //        model.addAttribute("test","list");
//        model.addAttribute("test2",0);
//        model.addAttribute("test3",list);
//        model.addAttribute("test4",list);
        return JSONObject.toJSONString(byId);
    }

    @RequestMapping("test8")
    @ResponseBody
    public String test8(Model model) {
        String result = HttpUtil.sendToPost(GET_COMMISSARY_FOOD_URL);
        String itemSetObject = JSONObject.parseObject(result, JSONObject.class).getString("itemSet");
        MenuFoodCategory menuFoodCategory = menuFoodCategoryService.query().eq("CODE", FOOD_CATEGORY_ID_CODE_xmb).one();
        int i = 0;
        if (itemSetObject != null) {
            List<MenuFoodItem> menuFoodItemList = JSONObject.parseArray(itemSetObject, MenuFoodItem.class);
            for (MenuFoodItem menuFoodItem : menuFoodItemList) {
                i++;
                if (i > 20) {
                    return "";
                }
                if (StringUtils.isEmpty(menuFoodItem.getBarCode())) {
                    continue;
                }
                MenuFoodItem code = menuFoodItemService.query().eq("CODE", menuFoodItem.getCode()).one();
                if (code != null) {
                    MenuFoodPrice foodPrice = menuFoodPriceService.query().eq("FOOD_ID", code.getId()).one();
                    foodPrice.setPrice(menuFoodItem.getSalePrice());
                    foodPrice.setEndTime(foodPrice.getEndTime().plusMonths(1));
                    menuFoodPriceService.updateById(foodPrice);
                } else {
                    menuFoodItem.setFoodCategoryId(menuFoodCategory.getId());
                    menuFoodItem.setMeasurementId("ec9b1ad1d13b475482c44f110327be0d");
                    menuFoodItem.setStatus("0");
                    menuFoodItem.setCreatorId("admin");
                    menuFoodItem.setCreatorName("系统管理员");
                    menuFoodItemService.save(menuFoodItem);
                    MenuFoodPrice foodPrice = new MenuFoodPrice();
                    foodPrice.setFoodId(menuFoodItem.getId());
                    foodPrice.setBusinessTypeId(COMMISSARY_BUSINESS_TYPE_ID);
                    foodPrice.setPrice(menuFoodItem.getSalePrice());
                    foodPrice.setStartTime(LocalDateTime.now());
                    foodPrice.setEndTime(LocalDateTime.now().minusMonths(1));
                    foodPrice.setLevel(0);
                    foodPrice.setCreateTime(LocalDateTime.now());
                    foodPrice.setMealTimeId("5a38f3931d9f4b05987d744cafccd80a");
                    foodPrice.setPriceVersion(System.currentTimeMillis());
                    foodPrice.setStatus("0");
                    foodPrice.setCreatorId("admin");
                    foodPrice.setCreatorName("系统管理员");
                    menuFoodPriceService.save(foodPrice);
                }


            }
            return "";


        } else {
            return "";
        }
    }


    @RequestMapping("print")
    public String print(Model model) {


        TradeConsumptionMain byId = tradeConsumptionMainService.getById("5cbdc24056f2401999967f4c6b1921ca");
//        smallTicketPrinter.printOrder(tradeConsumptionDetailService.findByMainId(byId.getId()), byId);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        QueryWrapper<TradeConsumptionMain> tradeConsumptionMainQueryWrapper = new QueryWrapper<>();
        tradeConsumptionMainQueryWrapper.eq("CREATE_TIME", df.format(byId.getCreateTime()));
        List<TradeConsumptionMain> list = tradeConsumptionMainService.list(tradeConsumptionMainQueryWrapper);
        //        model.addAttribute("test","list");
//        model.addAttribute("test2",0);
//        model.addAttribute("test3",list);
//        model.addAttribute("test4",list);
        return JSONObject.toJSONString(list);
    }

    static Runnable runnable = new Runnable() {
        int i = 0;

        @SneakyThrows
        @Override
        public void run() {
            while (i >= 0) {
                System.out.println(i++);
                Thread.sleep(5000);
            }
        }
    };

    static Thread thread = new Thread(runnable);


    public static void xiancheng() {
        thread.setDaemon(true);
        thread.start();
        thread.run();
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

//        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//校验数字
//        Matcher isNum = pattern.matcher("234567899876543");
//        System.out.println(isNum.matches());
//        System.out.println( new BigDecimal(10).compareTo(BigDecimal.ZERO) );
//        String code="287099281451009231";
//        System.out.println(  code.matches("/^(?:2[5-9]|30)\\d{14,18}$/"));
//        System.out.println(   Pattern.matches("/^(?:2[5-9]|30)\\d{14,18}$/", code));
//        Pattern  p= Pattern.compile("^[1][3578][0-9]{9}$");
//        Pattern  p1= Pattern.compile("^(2[5-9]|30)\\d{14,18}$");
//        Pattern  p2= Pattern.compile("^2+");
//        Matcher m=p.matcher("15955959595");
//        Matcher m1=p1.matcher("287099281451009231");
//        Matcher m2=p2.matcher("287099281451009231");
//        boolean b=m.matches();
//        boolean b1=m1.matches();
//        boolean b2=m2.matches();
//        System.out.println(b);
//        System.out.println(b1);
//        System.out.println(b2);
//        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        executorService.execute(runnable);
//        ExecutorService pool = Executors.newFixedThreadPool(1,
//                new ThreadFactory() {
//                    public Thread newThread(Runnable r) {
//                        Thread thread = new Thread(r);
//                        thread.setDaemon(true);
//                        thread.setName("threadNamePrefix" + thread.getId());
//                        return thread;
//                    }
//                });
//        pool.execute(runnable);
//        System.out.println(22222);
//        System.out.println(22222);
//        System.out.println(22222);
//        System.out.println(22222);
//        return;
        String sss = "啛啛三生三世";
//        sss = String.format("%-14s", sss);
//        sss += "222";
        String ssa = "&nbsp";
        System.out.println(sss);
        System.out.println(sss.getBytes("GBK").length / 2);
        Integer i = 4;
        System.out.println(Math.pow(10, i));
//        System.out.println(ssa.getBytes().length);

    }

    @RequestMapping("test5")
    public String test5() {


//        List<MenuFoodItem> menuFoodItem = menuFoodItemService.selectFoodItemList();
//        MenuFoodItem byId = menuFoodItemService.getById("1775ddab7c4547a3ad5fb53969b36747");

//        List<MenuFoodItem> foodItemList = menuFoodItemService.listXMBFood("6953787338429", FOOD_CATEGORY_ID_CODE_xmb);

//        List<CardAccount> CardAccount = cardAccountService.findCardAccountList("820c09b7a4294333b352c997d9613bda", "午餐");

        List<SystemRefundApproval> systemRefundApprovalList = systemRefundApprovalService.list();

        return JSONObject.toJSONString(systemRefundApprovalList);
    }

    @RequestMapping("test6")
    public String test6() {


        List<SystemRefundApproval> systemRefundApprovalList = systemRefundApprovalService.list();

        return JSONObject.toJSONString(systemRefundApprovalList);
    }

    @RequestMapping("test7")
    public String test7() {
        boolean admin = systemAclUserService.hasAuthority("2125675d72ef407ea6085b8136c3bec7", "adminS");


        return JSONObject.toJSONString(admin);
    }

    @RequestMapping("index")
    public String index() {
        return "/index";
    }


    @RequestMapping(value = "/test.do", method = RequestMethod.POST)
    public String wxpayQuery(Model model, HttpServletResponse response, HttpServletRequest request) {
        HashMap<String, String> map = new HashMap<>();
        List<TradeAccountConsumptionFlow> list = tradeAccountConsumptionFlowService.query()
                .eq("REASON_ID", "微信支付")
                .ge("CREATE_TIME", "2021-11-30 00:00:00").list();
        WXPayConfigImpl config = null;
        List<String> objects = new ArrayList<>();
        try {
            config = WXPayConfigImpl.getInstance();
            WXPay wxpay = new WXPay(config);
            for (TradeAccountConsumptionFlow tradeAccountConsumptionFlow : list) {
                map.put("out_trade_no", "7004029XF" + tradeAccountConsumptionFlow.getFlowNo());
                Map<String, String> ResultMap = wxpay.orderQuery(map);
                ResultMap = isSuccess(ResultMap, wxpay, map);
                if (!ResultMap.get("is_success").equals("YES")) {
                    System.err.printf(ResultMap.get("is_success") + "___________________________");
                    System.err.println(tradeAccountConsumptionFlow.getFlowNo());
                    objects.add(tradeAccountConsumptionFlow.getFlowNo());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(JSONObject.toJSONString(objects));

        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);

    }


    @RequestMapping(value = "/test3.do")
    @ResponseBody
    public String wxpayQuery3(@RequestParam("f") String f) {
        HashMap<String, String> map = new HashMap<>();
        WXPayConfigImpl config = null;

        try {
            config = WXPayConfigImpl.getInstance();
            WXPay wxpay = new WXPay(config);

            map.put("out_trade_no", f);
            Map<String, String> ResultMap = wxpay.orderQuery(map);
            ResultMap = isSuccess(ResultMap, wxpay, map);
            if (!"YES".equals(ResultMap.get("is_success"))) {
                System.err.printf(ResultMap.get("is_success") + "___________________________");
            }
            return ResultMap.get("is_success");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";

    }

    @RequestMapping("ttt")
    public void ttt() {

        QueryWrapper<MenuFoodItem> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("DESCRIPTION", "微信菜品");
        List<MenuFoodItem> list = menuFoodItemService.list(queryWrapper);

        for (MenuFoodItem m : list) {
            QueryWrapper<MenuFoodPrice> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("FOOD_ID", m.getId());

            MenuFoodPrice one = menuFoodPriceService.getOne(queryWrapper1, false);
            if (one == null) {
                MenuFoodPrice foodPrice = new MenuFoodPrice();
                foodPrice.setFoodId(m.getId());
                foodPrice.setMealTimeId("1819c9a9dc394f8e920ef17bd8d74188");
                foodPrice.setBusinessTypeId("663703ac303b4993b85a9c4a3535f193");
                foodPrice.setPrice(0);
                foodPrice.setLevel(0);
                foodPrice.setPriceVersion(System.currentTimeMillis());
                foodPrice.setStatus("0");
                foodPrice.setCreatorId("admin");
                foodPrice.setCreatorName("微信");
                foodPrice.setCreateTime(LocalDateTime.now());
                menuFoodPriceService.save(foodPrice);
            }


        }


    }


    @RequestMapping("tttt")
    public void tttt() {


        QueryWrapper<MenuFoodPrice> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("CREATOR_NAME", "微信");

        List<MenuFoodPrice> list = menuFoodPriceService.list(queryWrapper1);
        ArrayList<String> objects = new ArrayList<>();
        for (MenuFoodPrice item : list) {

            MenuFoodItem byId = menuFoodItemService.getById(item.getFoodId());
            objects.add(byId.getCode());

        }

        System.out.println(JSONObject.toJSONString(objects));


    }


    @RequestMapping("upaddress")
    public void upaddress(@RequestParam("flow") String flow, @RequestParam("address") String address) {


        QueryWrapper<TradeConsumptionMain> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("FLOW_NO", flow);
        TradeConsumptionMain list = tradeConsumptionMainService.getOne(queryWrapper1);
        if ("外卖".equals(list.getTakeMealType()) && "营养餐厅".equals(list.getCustomerAddress())) {
            list.setCustomerAddress(address.replace(",", "|"));
            list.setCustomerArchitecture(address.split(",")[0]);
            list.setCustomerFloor(address.split(",")[0]);
            tradeConsumptionMainService.updateById(list);
        }
    }


    public Map<String, String> isSuccess(Map<String, String> map, WXPay wxpay, Map<String, String> data) {
        if (map.get("return_code").equals("SUCCESS")) {// 通讯成功
            if (map.get("result_code").equals("SUCCESS")) {// 交易成功
                if (map.get("trade_state") == null) {
                    map.put("is_success", "YES");
                    System.err.println("111 ===" + map.get("is_success"));
                } else if (map.get("trade_state").equals("USERPAYING")) {
                    map.put("is_success", "UNKNOWN");
                    System.err.println("222 ===" + map.get("is_success"));
                } else if (map.get("trade_state").equals("SUCCESS")) {
                    map.put("is_success", "YES");
                    System.err.println("333 ===" + map.get("is_success"));
                }
                return map;
            } else if (map.get("result_code").equals("FAIL")) {
                String errCode = map.get("err_code");// 交易不明确,查询订单
                if (errCode.equals("USERPAYING") || errCode.equals("BANKERROR") || errCode.equals("SYSTEMERROR")) {
                    map.put("is_success", "UNKNOWN");
                    System.err.println("444 ===unKnown");
                    return map;
                }
            }
            System.err.println("555 ===FAIL");
            map.put("is_success", "NO");
            return map;
        } else {
            System.err.println("支付失败，请重新扫码! 666===FAIL");
            map.put("is_success", "NO");
            return map;
        }
    }


}
